package com.leo.common;

import com.leo.bean.EmailInfo;
import com.leo.bean.MessageInfo;
import com.leo.db.DaoMapperProxy;
import com.leo.mapper.UserMapper;
import com.leo.view.MessageContentView;
import com.leo.view.SendEmailView;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.geometry.Bounds;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TreeItem;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.text.Text;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wangss
 * @date 2023/02/19 11:24
 * @description 全局容器
 **/
public final class ApplicationContentUtil {

    private static final Map<String, Object> CONTENTMAP = new HashMap<>();

    /**
     * @description: 邮箱列表
     * @author: wangss
     * @date: 2023/2/23 22:01
     **/
    public static final List<String> EMAILLIST = new ArrayList<>();

    /**
     * 收件箱
     */
    public static final ObservableList<MessageInfo> receiveList = FXCollections.observableArrayList();
    /**
     * 草稿箱
     */
    public static final ObservableList<MessageInfo> draftList = FXCollections.observableArrayList();
    /**
     * 发件箱
     */
    public static final ObservableList<MessageInfo> sendList = FXCollections.observableArrayList();
    /**
     * 垃圾箱
     */
    public static final ObservableList<MessageInfo> garbageList = FXCollections.observableArrayList();

    /**
     * 好友列表
     */
    public static final List<String> friendList = new ArrayList<>();

    public static Object getContentMapValue(String key) {
        return CONTENTMAP.get(key);
    }

    public static void putContentMap(String key, Object value) {
        CONTENTMAP.put(key, value);
    }

    static {
        // 收件箱添加监听
        receiveList.addListener((ListChangeListener<MessageInfo>) c -> {
            while (c.next()) {
                if (c.wasAdded()) {
                    MessageInfo messageInfo = receiveList.get(c.getFrom());
                    MailViewUtils.inBoxRoot.getChildren().add(0, createTreeItem(messageInfo));
                } else if (c.wasUpdated()) {

                } else if (c.wasRemoved()) {
                    int count = MailViewUtils.inBoxRoot.getChildren().size();
                    int index = count - 1 - c.getFrom();
                    MailViewUtils.inBoxRoot.getChildren().remove(index);
                } else if (c.wasReplaced()) {

                }
            }
        });

        // 草稿箱添加监听
        draftList.addListener((ListChangeListener<MessageInfo>) c -> {
            while (c.next()) {
                if (c.wasAdded()) {
                    MessageInfo messageInfo = draftList.get(c.getFrom());
                    MailViewUtils.draftBoxRoot.getChildren().add(0, createTreeItem(messageInfo));
                } else if (c.wasUpdated()) {
                    System.out.println("我要更新");
                } else if (c.wasRemoved()) {
                    int count = MailViewUtils.draftBoxRoot.getChildren().size();
                    int index = count - 1 - c.getFrom();
                    MailViewUtils.draftBoxRoot.getChildren().remove(index);
                } else if (c.wasReplaced()) {
                    System.out.println("我被替代");
                }
            }
        });

        // 发件箱添加监听
        sendList.addListener((ListChangeListener<MessageInfo>) c -> {
            while (c.next()) {
                if (c.wasAdded()) {
                    MessageInfo messageInfo = sendList.get(c.getFrom());
                    MailViewUtils.sendBoxRoot.getChildren().add(0, createTreeItem(messageInfo));
                } else if (c.wasUpdated()) {

                } else if (c.wasRemoved()) {
                    int count = MailViewUtils.sendBoxRoot.getChildren().size();
                    int index = count - 1 - c.getFrom();
                    MailViewUtils.sendBoxRoot.getChildren().remove(index);
                } else if (c.wasReplaced()) {

                }
            }
        });

        // 垃圾箱添加监听
        garbageList.addListener((ListChangeListener<MessageInfo>) c -> {
            while (c.next()) {
                if (c.wasAdded()) {
                    MessageInfo messageInfo = garbageList.get(c.getFrom());
                    MailViewUtils.dustbinRoot.getChildren().add(0, createTreeItem(messageInfo));
                } else if (c.wasUpdated()) {

                } else if (c.wasRemoved()) {
                    int count = MailViewUtils.dustbinRoot.getChildren().size();
                    int index = count - 1 - c.getFrom();
                    MailViewUtils.dustbinRoot.getChildren().remove(index);
                } else if (c.wasReplaced()) {

                }
            }
        });
    }

    /**
     * @description: 创建邮件列表的展示形式
     **/
    public static TreeItem createTreeItem(MessageInfo messageInfo) {
        TreeItem item = new TreeItem("");

        GridPane gridPane = new GridPane();
        gridPane.setUserData(messageInfo);

        // 居中、组件水平距离和垂直距离
        gridPane.setAlignment(Pos.CENTER_LEFT);
        gridPane.setHgap(2);
        gridPane.setVgap(2);
        // 内边距
        gridPane.setPadding(new Insets(2, 2, 2, 2));
        gridPane.setBorder(new Border(new BorderStroke(Color.GRAY, BorderStrokeStyle.SOLID, new CornerRadii(5d), new BorderWidths(2))));
        // 给列设置样式
        ColumnConstraints columnConstraints0 = new ColumnConstraints();
        columnConstraints0.setFillWidth(true);
        columnConstraints0.setHgrow(Priority.NEVER);
        columnConstraints0.setMaxWidth(50);
        columnConstraints0.setMinWidth(10);
        gridPane.getColumnConstraints().add(columnConstraints0);

        ColumnConstraints columnConstraints1 = new ColumnConstraints();
        columnConstraints1.setFillWidth(true);
        columnConstraints1.setHgrow(Priority.NEVER);
        columnConstraints1.setMinWidth(100);
        columnConstraints1.setMaxWidth(100);
        gridPane.getColumnConstraints().add(columnConstraints1);

        ColumnConstraints columnConstraints2 = new ColumnConstraints();
        columnConstraints2.setFillWidth(true);
        columnConstraints2.setHgrow(Priority.NEVER);
        columnConstraints2.setMinWidth(50);
        columnConstraints2.setMaxWidth(50);
        gridPane.getColumnConstraints().add(columnConstraints2);

        // 给每行设置样式
        RowConstraints rowConstraints = new RowConstraints();
        rowConstraints.setFillHeight(true);
        rowConstraints.setVgrow(Priority.NEVER);
        for (int i = 0; i < 2; i++) {
            gridPane.getRowConstraints().add(rowConstraints);
        }

        int isRead = messageInfo.getIsRead();
        Circle readCircle = new Circle(3);
        if (0 == isRead) {
            readCircle.setFill(Color.GREEN);
        } else {
            readCircle.setFill(Color.GRAY);
        }
        gridPane.add(readCircle, 0, 0);

        String from = messageInfo.getEmailFrom();
        if (from.contains("<")) {
            from = from.substring(0, from.indexOf("<"));
        }
        if (from.contains("@")) {
            from = from.substring(0, from.indexOf("@"));
        }
        Text fromText = new Text(from);
        gridPane.add(fromText, 1, 0);

        String sendTime = messageInfo.getSendTime();
        Text sendTimeText = new Text(sendTime);
        gridPane.add(sendTimeText, 2, 0);

        Circle starCircle = new Circle(3, Color.YELLOW);
        gridPane.add(starCircle, 0, 1);

        String subject = messageInfo.getSubject();
        if (subject.length() > 10) {
            subject = subject.substring(0, 10) + "...";
        }
        Text subjectText = new Text(subject);
        gridPane.add(subjectText, 1, 1, 2, 1);

        item.setGraphic(gridPane);

        gridPane.setOnMouseClicked(event -> {
            // 点击两次，草稿箱
            if (2 == event.getClickCount()) {
                if (4 == messageInfo.getStatus()) {
                    EmailInfo mailBean = (EmailInfo) ApplicationContentUtil.getContentMapValue((String) ApplicationContentUtil.getContentMapValue("currentEmail"));
                    SendEmailView sendEmailView = new SendEmailView(mailBean, messageInfo);
                    return;
                }
            }
            MessageContentView contentView = (MessageContentView) ApplicationContentUtil.getContentMapValue("contentView");
            contentView.refreshView(messageInfo);
        });

        // 添加右键事件
        ContextMenu contextMenu = new ContextMenu();
        MenuItem delItem = new MenuItem("删除");
        contextMenu.getItems().add(delItem);
        delItem.setOnAction(event -> {
            UserMapper userMapper = DaoMapperProxy.getProxyInstance(UserMapper.class);
            if (0 == messageInfo.getStatus() || 2 == messageInfo.getStatus()) {
                receiveList.remove(messageInfo);
            } else if (3 == messageInfo.getStatus()) {
                sendList.remove(messageInfo);
            } else if (4 == messageInfo.getStatus()) {
                draftList.remove(messageInfo);
            } else {
                garbageList.remove(messageInfo);
                userMapper.delMessageInfo(messageInfo.getId());
                return;
            }
            garbageList.add(messageInfo);
            // 更新状态
            userMapper.updateMessageInfoStatus(1, messageInfo.getId());
        });

        gridPane.setOnContextMenuRequested(event -> {
            Bounds bounds = gridPane.localToScreen(gridPane.getBoundsInLocal());
            contextMenu.show(gridPane.getScene().getWindow(), bounds.getMaxX() - 110, bounds.getMaxY());
        });
        return item;
    }
}
